package com.thestore.h5tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.thestore.main.core.app.AppContext;
import com.thestore.main.core.datastorage.DataHelper;
import com.yhdplugin.app.BaseActivity;
import com.yhdplugin.util.EmbedHttpServer;
import com.yhdplugin.util.EmbedHttpServer.ResponseOutputStream;

/**
 * 开发调试启动入口
 * <p>
 * 
 * Intent参数：<br>
 * port:int，指定服务器的监听端口号，默认为5036<br>
 * 
 * @author yimin.tu
 * 
 */
public class DevLoaderActivity extends Activity {
	private TextView text;
	private static int port = 5036;
	private MainHttpServer server;
	private static String H5DIR = "h5content";
	private static String H5CFGNAME = "cfg.txt";
	private static String H5TEMP = "tmpfile";
	private File h5dir;
	private File tempDir;
	private Handler handler;
	private int max = 5;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//		text = new TextView(this);
		//		text.setLayoutParams(new ViewGroup.LayoutParams(
		//				ViewGroup.LayoutParams.MATCH_PARENT,
		//				ViewGroup.LayoutParams.MATCH_PARENT));
		setContentView(R.layout.activity_loader);
		text = (TextView)findViewById(R.id.txt_dis);
		h5dir = new File(AppContext.APP.getFilesDir(),H5DIR);
		if(!h5dir.exists())
		{
			h5dir.mkdir();
		}
		tempDir = new File(h5dir,H5TEMP);
		if(!tempDir.exists())
		{
			tempDir.mkdir();
		}
		else
		{
			//清理上次上传的文件
			this.DeleteFile(tempDir,false);
		}
		//启动socket服务
		server = new MainHttpServer(port);
		try {
			server.start();
			println("server started on port " + port);
		} catch (Exception e) {
			print("unable to start server on port " + port + ": ");
			println(e);
		}

		handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if(max == 1)
				{
					print(max);
				}
				else
				{
					print(max+",");
				}
				max--;
				if(max == 0)
				{

					Intent i = new Intent(DevLoaderActivity.this, MainActivity.class);
					goToActivity(i);
					finish();
				}
				else
				{
					handler.sendMessageDelayed(handler.obtainMessage(1), 1000);
				}
			}

		};
	}

	@Override
	public void onDestroy() {
		try {
			server.stop();
		} catch (Exception e) {
		}
		super.onDestroy();
	}

	private void print(final Object obj) {
		if (Thread.currentThread().getId() == Looper.getMainLooper()
				.getThread().getId()) {
			text.append(String.valueOf(obj));
		} else {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					print(obj);
				}
			});
		}
	}

	private void println(final Object obj) {
		if (Thread.currentThread().getId() == Looper.getMainLooper()
				.getThread().getId()) {
			text.append(String.valueOf(obj));
			text.append("\n");
		} else {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					println(obj);
				}
			});
		}
	}

	private void goToActivity(final Intent i)
	{
		if (Thread.currentThread().getId() == Looper.getMainLooper()
				.getThread().getId()) {
			startActivity(i);
		} else {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					startActivity(i);
				}
			});
		}
	}
	private class MainHttpServer extends EmbedHttpServer {

		int fnum = 0;
		int i=0;
		public MainHttpServer(int port) {
			super(port);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected void handle(String method, String path,
				HashMap<String, String> headers, InputStream input,
				ResponseOutputStream response) throws Exception {

			if(!headers.containsKey("filenum"))
			{
				println("no filenum recived,please check!");
			}
			else
			{
				if(fnum == 0)
				{
					fnum = Integer.parseInt(headers.get("filenum"));
				} 

				// Http请求处理
				if ("PUT".equalsIgnoreCase(method))
				{
					//上传文件的处理
					String fileName = path;
//					println("");
					println(String.format("start recive %s", fileName));
					File f = new File(tempDir,fileName);
					FileOutputStream fos = new FileOutputStream(f);
					byte[] buf = new byte[4096];
					int l;
					while ((l = input.read(buf)) != -1) {
						fos.write(buf, 0, l);
					}
					fos.close();
					println(f.length() + " bytes recived");
					println("suc");
//					println("");
					i++;
					if(i==fnum)
					{
						println(String.format("%d files rec completed!",i));
						println("");
						println("prepara h5 app......");
						Map<String,String> cfg = handZipFile();
						if(cfg == null)
						{
							println("prepara h5 app fail because unzip failed!!");
						}
						else
						{
							cfg = saveCfgFile(cfg);
							if(cfg != null)
							{
								println("i am success!i will go to h5package list page!");
								handler.sendMessageDelayed(handler.obtainMessage(1), 1000);

							}
							else
							{
								println("prepara h5 app fail because create cfg failed!!");
							}
						}
						//跳转到mainactivity

					}
				};
			}
		}

		public Map<String,String> saveCfgFile(Map<String,String> data)
		{

			File cfg = new File(h5dir,H5CFGNAME);
			if(cfg.exists())
			{
				//先读取在处理
				try {
					HashMap<String, String> old = DataHelper.gson.fromJson(
							new InputStreamReader(new FileInputStream(cfg)),
							new TypeToken<HashMap<String, String>>() {
							}.getType());
					cfg.delete();
					old.putAll(data);
					saveToFile(h5dir,H5CFGNAME,DataHelper.gson.toJson(old));
					return  old;
				} catch (JsonIOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonSyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
			else
			{
				//直接存储
				saveToFile(h5dir,H5CFGNAME,DataHelper.gson.toJson(data));
				return data;
			}

		}

		/*
		 * 文本内容存储到指定的路径及文件
		 */
		private boolean saveToFile(File path,String filename,String content){ 
			try{ 
				File f = new File(path,filename); 
				FileOutputStream out = new FileOutputStream(f); 
				out.write(content.getBytes("UTF-8")); 
				out.close(); 
				return true;
			} 
			catch(Exception e){ 
				return false;
			}
		}

		/*
		 * 从文本文件读取文本
		 */
		private String readTxtFile(File f)
		{
			try{ 
				FileInputStream in = new FileInputStream(f); 
				byte[]data = read2byte(in); 
				in.close();
				return new String(data,"UTF-8"); 
			} 
			catch(Exception e){ 
				return "";
			} 
		}

		private byte[] read2byte(InputStream in) throws IOException { 
			byte[] data; 
			ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
			byte[]buf = new byte[1024]; 
			int len = 0; 
			while((len = in.read(buf))!=-1){ 
				bout.write(buf, 0, len); 
			} 
			data = bout.toByteArray(); 
			bout.close();
			return data; 
		}

		private Map<String,String> handZipFile()
		{
			if(tempDir.listFiles().length == 0)
			{
				println("no h5 app to be prepared!please check");
				return null;
			}
			else
			{
				Map<String,String> rtn = new HashMap<String,String>();
				for(File f : tempDir.listFiles())
				{
					if(com.thestore.main.core.h5package.PkgUtil.unzip(f, h5dir))
					{
						//解压缩成功
						String fName = f.getName();
						String tname = fName.substring(0,fName.lastIndexOf("."));
						File h5folder = new File(h5dir,tname);
						if(h5folder.isDirectory())
						{
							h5folder = new File(h5folder,"h5cfg.txt");
							try {
								HashMap<String, String> h5Cfg = DataHelper.gson.fromJson(
										new InputStreamReader(new FileInputStream(h5folder)),
										new TypeToken<HashMap<String, String>>() {
										}.getType());
								rtn.putAll(h5Cfg);
							} catch (JsonIOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonSyntaxException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					}
					else
					{
						println(String.format("deploy %s fail!", f.getName()));
						return null;
					}
				}
				return rtn;
			}
		}

	}
	private void DeleteFile(File file,boolean delself) { 
		if (file.exists() == false) { 
			return; 
		} else { 
			if (file.isFile()) { 
				file.delete(); 
				return; 
			} 
			if (file.isDirectory()) { 
				File[] childFile = file.listFiles(); 
				if (childFile == null || childFile.length == 0) {
					if(delself)
					{
						file.delete(); 
					}
					return; 
				} 
				for (File f : childFile) { 
					DeleteFile(f,true); 
				} 
				if(delself)
				{
					file.delete(); 
				}
				//file.delete(); 
			} 
		}
	}
}
